const mysql = require('mysql');
const fs = require('fs').promises;
const path = require('path');

async function initDatabase() {
  // 创建数据库连接
  const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456'
  });

  try {
    // 读取 SQL 文件
    console.log('Reading SQL file...');
    const sqlFile = path.join(__dirname, 'init.sql');
    const sqlContent = await fs.readFile(sqlFile, 'utf8');

    // 分割 SQL 命令
    const commands = sqlContent
      .split(';')
      .map(cmd => cmd.trim())
      .filter(cmd => cmd.length > 0);

    console.log(`Found ${commands.length} SQL commands to execute.`);

    // 依次执行每条 SQL 命令
    for (let i = 0; i < commands.length; i++) {
      const command = commands[i];
      try {
        await new Promise((resolve, reject) => {
          connection.query(command, (err, results) => {
            if (err) {
              // 忽略"数据库已存在"错误
              if (err.code === 'ER_DB_CREATE_EXISTS') {
                console.log('Database already exists, continuing...');
                resolve();
              } else {
                reject(err);
              }
            } else {
              console.log(`[${i + 1}/${commands.length}] Successfully executed command`);
              resolve(results);
            }
          });
        });
      } catch (err) {
        console.error(`Error executing command: ${command.substring(0, 50)}...`);
        console.error(`Error message: ${err.message}`);
        if (err.code !== 'ER_TABLE_EXISTS_ERROR') {
          throw err;
        } else {
          console.log('Table already exists, continuing...');
        }
      }
    }

    console.log('Database initialization completed successfully!');
  } catch (err) {
    console.error('Fatal error:', err);
    process.exit(1);
  } finally {
    // 关闭数据库连接
    connection.end();
    console.log('Database connection closed.');
  }
}

// 处理未捕获的异常
process.on('unhandledRejection', (err) => {
  console.error('Unhandled promise rejection:', err);
  process.exit(1);
});

// 执行初始化
initDatabase().catch(err => {
  console.error('Initialization failed:', err);
  process.exit(1);
}); 